/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package caa.struts.course.action;

import caa.struts.course.form.ManageCourseForm;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.actions.DispatchAction;
import th.com.entity.CourseEntity;
import th.com.entity.LocationEntity;
import th.com.entity.ScheduleEntity;
import th.com.entity.SemesterEntity;
import th.com.entity.SubjectEntity;
import th.com.entity.UserEntity;
import th.com.ku.CAAService;

/**
 *
 * @author Ketsaraporn
 */
public class CourseManageAction extends DispatchAction {

    public ActionForward doAddCourse(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        ManageCourseForm addCourseForm = (ManageCourseForm) form;

        ArrayList<LocationEntity> locationList = CAAService.selectLocation();
        addCourseForm.setLocationList(locationList);

        if (!addCourseForm.getKwKeyWordSubject().equalsIgnoreCase("")) {
            List<SubjectEntity> rs = CAAService.selectSubjectForCourse(addCourseForm.getKwKeyWordSubject());
            if(!rs.isEmpty()) {
                addCourseForm.getCourseEntity().setSubId(addCourseForm.getKwKeyWordSubject());
            }
            addCourseForm.setSubjectList(new ArrayList<SubjectEntity>(rs));
        } else {
            addCourseForm.setSubjectList(new ArrayList<SubjectEntity>());
        }

//        String rs = CAAService.createCourse(addCourseForm.getCourseEntity());
//        addCourseForm.setCourseEntity(new CourseEntity());


        return mapping.findForward("addcourse.success");

    }

    public ActionForward doCreateCourse(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        ManageCourseForm addCourseForm = (ManageCourseForm) form;
        String userId = ((UserEntity)request.getSession().getAttribute("isUsername")).getUseId();
        
        addCourseForm.getCourseEntity().setCouCreatedBy(userId);
        CAAService.createCourse(addCourseForm.getCourseEntity(), addCourseForm.getSemesterEntity(), addCourseForm.getListScheule());
        
        

        return mapping.findForward("managecourse.success");

    }
    
    public ActionForward doLoadData(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        ManageCourseForm addCourseForm = (ManageCourseForm) form;
        
        if(addCourseForm.getCouId() == 0) {
            addCourseForm.setCourseEntity(new CourseEntity());
            addCourseForm.setSemesterEntity(new SemesterEntity());
            addCourseForm.setListScheule(new ArrayList<ScheduleEntity>());
            addCourseForm.setSelectTeacher(new ArrayList<UserEntity>());
        } else {
            addCourseForm.getCourseEntity().setCouId(addCourseForm.getCouId());
            addCourseForm.setCourseEntity(CAAService.findCourse(addCourseForm.getCourseEntity()));

            List<SubjectEntity> rs = CAAService.selectSubjectForCourse(addCourseForm.getCourseEntity().getSubId());
            addCourseForm.setSubjectList(new ArrayList<SubjectEntity>(rs));

            addCourseForm.getSemesterEntity().setSemId(addCourseForm.getCourseEntity().getSemId());
            addCourseForm.setSemesterEntity(CAAService.findSemester(addCourseForm.getSemesterEntity()));

            addCourseForm.setSelectTeacher(CAAService.findCourseUseDistinct(addCourseForm.getCourseEntity()));

            ScheduleEntity scheduleEntity = new ScheduleEntity();
            scheduleEntity.setCouId(addCourseForm.getCourseEntity().getCouId());
            addCourseForm.setListScheule(CAAService.findSchedule(scheduleEntity));
        }
        
        return mapping.findForward("addcourse.success");

    }

    public ActionForward doEditCourse(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        ManageCourseForm addCourseForm = (ManageCourseForm) form;
        String userId = ((UserEntity)request.getSession().getAttribute("isUsername")).getUseId();
        
        addCourseForm.getCourseEntity().setCouModifyBy(userId);
        addCourseForm.getSemesterEntity().setSemModifyBy(userId);
        String rs = CAAService.updateCourse(addCourseForm.getCourseEntity(), addCourseForm.getSemesterEntity(), addCourseForm.getListScheule());

        return mapping.findForward("managecourse.success");

    }

    public ActionForward goDetail(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        ManageCourseForm addCourseForm = (ManageCourseForm) form;
        

        ArrayList<Integer> listDays = new ArrayList<Integer>();
        if (addCourseForm.getCourseEntity().getCouDaySun() != null) {
            listDays.add(Calendar.SUNDAY);
        }
        if (addCourseForm.getCourseEntity().getCouDayMon() != null) {
            listDays.add(Calendar.MONDAY);
        }
        if (addCourseForm.getCourseEntity().getCouDayTue() != null) {
            listDays.add(Calendar.TUESDAY);
        }
        if (addCourseForm.getCourseEntity().getCouDayWed() != null) {
            listDays.add(Calendar.WEDNESDAY);
        }
        if (addCourseForm.getCourseEntity().getCouDayThu() != null) {
            listDays.add(Calendar.THURSDAY);
        }
        if (addCourseForm.getCourseEntity().getCouDayFri() != null) {
            listDays.add(Calendar.FRIDAY);
        }
        if (addCourseForm.getCourseEntity().getCouDaySat() != null) {
            listDays.add(Calendar.SATURDAY);
        }

        if (!listDays.isEmpty()) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(addCourseForm.getCourseEntity().getCouBeginDate());
//        System.out.println("getTime = "+cal.getTime());
            int numberDate = 0;
            ArrayList<ScheduleEntity> listNew = new ArrayList<ScheduleEntity>();
            while (true) {
                int startDate = cal.get(Calendar.DAY_OF_WEEK);
                for (Integer integer : listDays) {
//                System.out.println("startDate = "+startDate);
//                System.out.println("integer = "+integer.intValue());
                    if (startDate == integer.intValue()) {
                        ScheduleEntity entity = new ScheduleEntity();
                        entity.setSchTeachDate(new java.sql.Date(cal.getTime().getTime()));
                        entity.setSchBeginTime(addCourseForm.getCourseEntity().getCouBeginTime());
                        entity.setSchEndTime(addCourseForm.getCourseEntity().getCouEndTime());
                        listNew.add(entity);
                        
                        ScheduleEntity oldEntity = addCourseForm.getListScheule().get(numberDate);
                        entity.setCouUseId(oldEntity.getCouUseId());
                        entity.setUserId(oldEntity.getUserId());
                        entity.setSchId(oldEntity.getSchId());
                        numberDate++;
                        break;
                    }
                }
                if (numberDate == 15) {
                    break;
                }
                cal.add(Calendar.DAY_OF_WEEK, 1);
            }
            addCourseForm.setListScheule(listNew);
        }

        return mapping.findForward("addcourse.success");

    }

    public ActionForward doManageCourse(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        ManageCourseForm addCourseForm = (ManageCourseForm) form;
        
        addCourseForm.setCourseEntity(new CourseEntity());
        addCourseForm.setSemesterEntity(new SemesterEntity());
        addCourseForm.setListScheule(new ArrayList<ScheduleEntity>());
        addCourseForm.setSelectTeacher(new ArrayList<UserEntity>());
        
        addCourseForm.setKwKeyWordSubject("");
        addCourseForm.setSubjectList(new ArrayList<SubjectEntity>());
        
        ArrayList<LocationEntity> locationList = CAAService.selectLocation();
        addCourseForm.setLocationList(locationList);

        List<CourseEntity> rs = CAAService.selectCourse(addCourseForm.getKwKeyWord());
        addCourseForm.setCourseList(new ArrayList<CourseEntity>(rs));

        return mapping.findForward("managecourse.success");

    }

    public ActionForward doDeleteCourse(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        ManageCourseForm addCourseForm = (ManageCourseForm) form;
        
        String rs = CAAService.deleteCourse(addCourseForm.getCouId());

        return mapping.findForward("managecourse.do");

    }

    public ActionForward doPreviewCourse(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        ManageCourseForm addCourseForm = (ManageCourseForm) form;
        List<CourseEntity> rs = CAAService.selectCoursePreview(addCourseForm.getUserId());
        addCourseForm.setCourseEntity(rs.get(0));
        return mapping.findForward("previewcourse.success");
    }

    public ActionForward doAddTeacher(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("test");
        ManageCourseForm addCourseForm = (ManageCourseForm) form;
        ActionErrors errors = new ActionErrors();
        ActionForward forward = new ActionForward();
        forward = mapping.findForward("addteacher.success");

        ArrayList<UserEntity> listAll = CAAService.findTeacher("");
        addCourseForm.setUserList(listAll);

        if (!addCourseForm.getKwKeyCourse().equalsIgnoreCase("") && addCourseForm.getKwKeyCourseSelect().equalsIgnoreCase("")) {
            ArrayList<UserEntity> listOne = CAAService.findTeacher(addCourseForm.getKwKeyCourse());
            if (listOne.isEmpty()) {
                errors.add("", new ActionMessage("errors.detail", addCourseForm.getKwKeyCourse() + " รหัสอาจารย์ไม่ถูกต้อง"));
            } else {
                addCourseForm.getSelectTeacher().add(listOne.get(0));
                forward = mapping.findForward("addcourse.success");
            }
        } else if (!addCourseForm.getKwKeyCourseSelect().equalsIgnoreCase("")) {
            for (UserEntity entity : addCourseForm.getUserList()) {
                if (entity.getUseId().equalsIgnoreCase(addCourseForm.getKwKeyCourseSelect())) {
                    addCourseForm.getSelectTeacher().add(entity);
                    break;
                }
            }
            forward = mapping.findForward("addcourse.success");
        }
        saveErrors(request, errors);

        return forward;

    }

    public ActionForward doDelTeacher(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        ManageCourseForm addCourseForm = (ManageCourseForm) form;

        ArrayList<UserEntity> list = addCourseForm.getSelectTeacher();
        list.remove(Integer.valueOf(addCourseForm.getTeachRowId()).intValue());
        addCourseForm.setSelectTeacher(list);

        return mapping.findForward("addcourse.success");
    }
}
